/*
 * @Author: Qi
 * @Date: 2023-02-06 11:02:58
 * @LastEditTime: 2023-03-04 10:05:04
 * @Description: axios请求封装
 */
import axios from 'axios'
import type {
  AxiosInstance,
  AxiosError,
  AxiosRequestConfig,
  AxiosResponse,
} from 'axios'
import merge from 'lodash'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { ResultEnum } from '@/enums/httpEnums'
import { ResultData } from './type'
import { LOGIN_URL } from '@/config/config'
// import { useRouter } from 'vue-router'
import router from '@/router'
import { RESEETSTORE } from '../reset'
import qs from 'qs'
// axios.defaults.headers = {'Content-Type': 'application/json; charset=utf-8'}
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
const service: AxiosInstance = axios.create({
  // baseURL: 'http://47.93.63.24/apis',
  // baseURL: 'http://47.93.63.24/apis',
  baseURL: import.meta.env.VITE_APP_NODE_ENV=='development'?import.meta.env.VITE_APP_BASE_API:import.meta.env.VITE_APP_NODE_URL,
  timeout: ResultEnum.TIMEOUT as number,
  withCredentials:true,
  headers:{
    'Content-Type' :'application/x-www-form-urlencoded; charset=utf-8'
  }
})

/**
 * @description: 请求拦截器
 * @returns {*}
 */
service.interceptors.request.use(
  (config:any) => {
    console.log(config);
    
    const userStore = useUserStore()
    const token = userStore.token
    if (token) {
      config.headers.token = token
    }
    // if (!config.url.startsWith('http')) {
    //   // console.log(config.url,'config.url');
      
    //   config.url = import.meta.env.VITE_APP_BASE_API + config.url
    //   console.log(config.url);
      
    // }
    const type = config.method
    const defaults = {}
    const arrayFormat = config.headers.arrayFormat || 'indices'
    if (type === 'post' && config.headers['Content-Type'] === 'application/x-www-form-urlencoded; charset=utf-8') {
      // post请求参数处理
      config.data = qs.stringify(config.data, { allowDots: true, arrayFormat: arrayFormat })
    } else if (type === 'get') {
      // get请求参数处理
      config.params = qs.stringify(config.params, { allowDots: true, arrayFormat: arrayFormat })
      config.params = qs.parse(config.params)
      config.params = merge.merge(defaults, config.params)
    }
    return config
  },
  (error: AxiosError) => {
    ElMessage.error(error.message)
    return Promise.reject(error)
  },
)
/**
 * @description: 响应拦截器
 * @returns {*}
 */
service.interceptors.response.use(
  
  (response: AxiosResponse) => {
    console.log(response);
    if(response.config.responseType=='blob'){
      return response
    }
    const { data } = response
    // const router = useRouter()
    // * 登陆失效（code == 401）
    if (data.code == ResultEnum.OVERDUE) {
      RESEETSTORE()
      router.replace(LOGIN_URL)
      return Promise.reject(data)
    }
    
    if (data.code && data.code == ResultEnum.SUCCESS) {
      ElMessage.error(data.message || ResultEnum.ERRMESSAGE)
      return Promise.reject(data)
    }
    return data
  },
  (error: AxiosError) => {
    // 处理 HTTP 网络错误
    let message = ''
    // HTTP 状态码
    const status = error.response?.status
    switch (status) {
      case 401:
        message = 'token 失效，请重新登录'
        break
      case 403:
        message = '拒绝访问'
        break
      case 404:
        message = '请求地址错误'
        break
      case 500:
        message = '服务器故障'
        break
      default:
        message = '网络连接故障'
    }

    ElMessage.error(message)
    return Promise.reject(error)
  },
)

/**
 * @description: 导出封装的请求方法
 * @returns {*}
 */
const http = {
  get<T>(url: string, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return service.get(url, config)
  },
  // get<T>(
  //   url: string,
  //   data?: object,
  //   config?: AxiosRequestConfig,
  // ): Promise<ResultData<T>> {
  //   return service({
  //     method:'get',
  //     url,
  //     params:data,
      
  //   })
  // },
  post<T>(
    url: string,
    data?: object,
    config?: AxiosRequestConfig,
  ): Promise<ResultData<T>> {
    return service.post(url, data, config)
  },

  put<T>(
    url: string,
    data?: object,
    config?: AxiosRequestConfig,
  ): Promise<ResultData<T>> {
    return service.put(url, data, config)
  },

  delete<T>(url: string, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return service.delete(url, config)
  },
}

export default http
